<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="title"
    @ok="handleSubmit"
    @cancel="handleCancel"
    destroyOnClose
    :defaultFullscreen="true"
    @visible-change="handleVisibleChange"
  >
    <a-row>
      <a-col :sm="16" :md="15" :lg="15" :xl="18">
        <BasicForm @register="registerForm" />
        <div style="margin-left: 12px; margin-right: 50px">
          <div style="display: inline-block; margin-bottom: 5px">
            <a-button type="link" size="small" href="https://www.cnblogs.com/codingsilence/archive/2011/03/29/2146580.html" target="_blank">
              Velocity语法
            </a-button>
            <span class="split">|</span>
            快捷键：<a-tag color="blue" v-for="item in shortcutKeyList" style="margin-right: 5px">{{ item }}</a-tag>
          </div>
          <MyAceEditor ref="editor" v-model:content="content" :style="aceEditorStyle" />
        </div>
      </a-col>
      <!-- background-color: red; -->
      <a-col :sm="10" :md="8" :lg="8" :xl="6" style="margin-top: 5px">
        <div :class="{ hasFix: needFix }" style="font-size: 14px">
          <h4 style="margin: 5px 0">
            Velocity变量
            <span class="velocity-tip"> 点击变量直接插入 </span>
          </h4>
          <a-tabs @tab-click="handleTabClick">
            <a-tab-pane v-for="item in velocityVariable" :key="item.key" :tab="item.tab" />
          </a-tabs>
          <div class="velocity-var">
            <a-tree class="draggable-tree" draggable block-node :expanded-keys="expandedKeys" @expand="handleExpand" :tree-data="variableTreeData">
              <template #title="{ expression, text, children, isClickInsert }">
                <span v-if="children && children.length > 0">
                  <a v-if="isClickInsert" @click="handleExpressionClick(expression)">{{ text }}</a>
                  <span v-else>{{ text }}</span>
                </span>
                <span v-else>
                  <a @click="handleExpressionClick(expression)">{{ text }}</a>
                </span>
              </template>
            </a-tree>
          </div>
        </div>
      </a-col>
    </a-row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onUnmounted } from "vue"
  import lodash from "lodash"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import MyAceEditor from "/@/components/My/MyAceEditor.vue"
  import { formSchema } from "./template.data"
  import { saveOrUpdateTemplate, getTemplateById, listVelocityVar } from "./template.api"
  import { listTemplateGroup } from "../templateGroup/templateGroup.api"
  import { useMessage } from "/@/hooks/web/useMessage"

  const editor = ref()
  const aceEditorStyle = ref<String>("width: 100%; height: calc(100vh - 320px)")

  const { createMessage } = useMessage()
  // Emits声明
  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)
  const content = ref("")
  const velocityVariable = ref([])
  const variableTreeData = ref([])
  const expandedKeys = ref<string[]>([])
  let timer
  //表单配置
  const [registerForm, { getFieldsValue, resetFields, validateFields, setFieldsValue, validate, updateSchema }] = useForm({
    // labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  })
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      //获取详情
      data.record = await getTemplateById({ id: data.record.id })
      content.value = data.record.content
      //表单赋值
      await setFieldsValue({
        ...data.record,
      })
    }
    const option = await listTemplateGroup({})
    await updateSchema({
      field: "groupId",
      componentProps: {
        optionFilterProp: "label",
        showSearch: true,
        options: unref(option),
      },
    })

    velocityVariable.value = await listVelocityVar()
    variableTreeData.value = velocityVariable.value[0].varList
    console.log("velocityVariable: ", velocityVariable.value)
    if (isUpdate.value) {
      timer = window.setInterval(async () => {
        if (content.value === "") {
          createMessage.warning("模板内容不能为空")
          return
        }
        let values = await validate()
        //提交表单
        await saveOrUpdateTemplate({ ...values, content: content.value }, isUpdate.value)
        console.log("定时保存成功")
      }, 3000)
    }
  })
  const needFix = ref(true)
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? "新增模板" : "编辑模板"))
  const shortcutKeyList = ref(["删除当行(Ctrl+D)", "复制当行(Alt-Shift-Down)"])

  const handleTabClick = (activeKey) => {
    velocityVariable.value.forEach((x) => {
      if (x.key === activeKey) {
        variableTreeData.value = x.varList
      }
    })
  }

  const handleVisibleChange = (b) => {
    console.log("clearInterval")
    window.clearInterval(timer)
    timer = null
  }

  const handleCancel = (e) => {
    window.clearInterval(timer)
    timer = null
    editor.value.reset()
  }

  onUnmounted(() => {
    console.log("onUnmounted")
    window.clearInterval(timer)
    timer = null
  })

  //表单提交事件
  async function handleSubmit(v) {
    try {
      if (content.value === "") {
        createMessage.warning("模板内容不能为空")
        return
      }
      let values = await validate()
      setModalProps({ confirmLoading: true })
      //提交表单
      await saveOrUpdateTemplate({ ...values, content: content.value }, isUpdate.value)
      //关闭弹窗
      closeModal()
      window.clearInterval(timer)
      timer = null
      createMessage.success("保存成功")
      editor.value.reset()
      //刷新列表
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }

  const handleExpand = (keys: string[], { expanded, node }) => {
    const tempKeys = ((node.parent ? node.parent.children : variableTreeData.value) || []).map(({ key }) => key)
    if (expanded) {
      expandedKeys.value = lodash.difference(keys, tempKeys).concat(node.key)
    } else {
      expandedKeys.value = keys
    }
  }

  const handleExpressionClick = (expression) => {
    console.log("expression: ", expression)
    editor.value.insert(expression)
  }
</script>

<style>
  span.split {
    color: #ccc;
    margin: 0 3px;
  }
  .hasFix {
    /* position: fixed; */
    position: absolute;
    overflow-y: auto;
    top: 80px;
    bottom: 0px;
  }
  .velocity-tip {
    color: #606266;
    font-size: 13px;
    font-weight: normal;
  }

  .velocity-var li {
    font-size: 14px;
    color: #606266;
    line-height: 26px;
  }
  .velocity-var a {
    color: #409eff;
    font-weight: 500;
  }
  .velocity-var a:hover {
    color: rgba(64, 158, 255, 0.75);
  }
  .velocity-var-container {
    overflow-y: auto;
  }
</style>
